# -*- coding: utf-8 -*-
"""
@Time： 2023/12/20 16:20
@Auth： gubei
@File： debug.py
@IDE：PyCharm
@Description：开发环境启动文件
"""
import argparse
import logging
import os
import sys
from pathlib import Path

import uvicorn

# 避免循环导入
# from core.server import InitializeApp
from core.log import logger, InterceptHandler, loguru_config
from env import setting
from utils.logger import Log

# 获取项目根目录
project_root = Path(__file__).parent
# 确保日志目录存在
LOG_DIR = project_root / "logs"
os.makedirs(LOG_DIR, exist_ok=True)


def create_debug_entry_point():
    """
    创建一个临时的入口点文件，用于热重载模式
    这个文件将被uvicorn加载并重载，确保正确的初始化序列
    """
    # 创建debug_entry.py
    entry_file = project_root / "debug_entry.py"
    with open(entry_file, "w", encoding="utf-8") as f:
        f.write("""# -*- coding: utf-8 -*-
\"\"\"
临时入口点文件
用于uvicorn热重载
\"\"\"
import logging
import os
import sys
from pathlib import Path

# 将项目目录添加到路径
project_root = Path(__file__).resolve().parent
if str(project_root) not in sys.path:
    sys.path.append(str(project_root))

from core.log import logger, InterceptHandler
from utils.logger import Log
from core.server import InitializeApp

# 初始化日志
def init_logger():
    \"\"\"初始化日志配置\"\"\"
    # 配置uvicorn日志使用loguru
    LOGGER_NAMES = ("uvicorn", "uvicorn.access", "uvicorn.error", "fastapi")
    logging.getLogger().handlers = [InterceptHandler()]
    for logger_name in LOGGER_NAMES:
        logging_logger = logging.getLogger(logger_name)
        logging_logger.handlers = [InterceptHandler()]
        # 调整Uvicorn日志级别，隐藏一些不必要的消息
        if logger_name in ("uvicorn", "uvicorn.access"):
            logging_logger.setLevel(logging.WARNING)
    
    # 尝试配置loguru (如果尚未配置)
    try:
        # 仅当未配置时进行配置
        if len(logger._core.handlers) <= 1:
            Log.configure_logger()
        logger.info("日志系统初始化完成")
    except Exception as e:
        print(f"日志系统初始化失败: {str(e)}")

# 初始化日志
init_logger()

# 创建应用实例
app = InitializeApp()

# 打印启动信息
display_ip = "127.0.0.1"  # 默认值
try:
    import socket
    hostname = socket.gethostname()
    display_ip = socket.gethostbyname(hostname)
except:
    pass

logger.success(f"应用入口点已加载，可访问: http://{display_ip}:10161/docs")
""")
    return "debug_entry:app"


def configure_logging():
    """配置日志系统"""
    # 配置uvicorn日志使用loguru
    LOGGER_NAMES = ("uvicorn", "uvicorn.access", "uvicorn.error", "fastapi")
    logging.getLogger().handlers = [InterceptHandler()]
    for logger_name in LOGGER_NAMES:
        logging_logger = logging.getLogger(logger_name)
        logging_logger.handlers = [InterceptHandler()]
        # 调整Uvicorn日志级别，隐藏一些不必要的消息
        if logger_name in ("uvicorn", "uvicorn.access"):
            logging_logger.setLevel(logging.WARNING)
    
    # 配置loguru
    try:
        # 仅当未配置时进行配置
        if len(logger._core.handlers) <= 1:
            Log.configure_logger()
    except Exception as e:
        print(f"日志初始化失败: {str(e)}")


def parse_arguments():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description="YHPC后端开发服务器")
    parser.add_argument(
        "--host", 
        default="0.0.0.0",
        help="监听主机地址 (默认: 0.0.0.0)"
    )
    parser.add_argument(
        "--port", 
        type=int, 
        default=10161,
        help="监听端口 (默认: 10161)"
    )
    parser.add_argument(
        "--no-reload", 
        action="store_true",
        help="禁用代码热重载"
    )
    parser.add_argument(
        "--quiet", 
        action="store_true",
        help="安静模式，减少日志输出"
    )
    return parser.parse_args()


def start_server(args):
    """启动服务器"""
    # 配置日志系统
    configure_logging()
    
    # 使用更安全的属性获取
    access_log = False if args.quiet else True
    log_level = "error" if args.quiet else "warning"
    
    # 记录基本信息
    logger.success(f"启动开发服务器: http://{args.host}:{args.port}")
    logger.info(f"热重载: {'禁用' if args.no_reload else '启用'}")
    
    # 热重载模式：需要使用字符串引用
    reload_mode = not args.no_reload
    if reload_mode:
        # 创建临时入口点文件
        app_import = create_debug_entry_point()
        
        # 热重载模式下使用字符串导入
        uvicorn.run(
            app=app_import,
            host=args.host,
            port=args.port,
            reload=True,
            reload_dirs=[str(project_root)],
            forwarded_allow_ips="*",
            access_log=access_log,
            log_level=log_level
        )
    else:
        # 非热重载模式下使用简单的应用启动
        logger.info("使用非热重载模式启动服务器")
        
        # 导入应用
        from core.server import InitializeApp
        app = InitializeApp()
        
        # 启动服务器
        uvicorn.run(
            app=app,
            host=args.host,
            port=args.port,
            reload=False,
            forwarded_allow_ips="*",
            access_log=access_log,
            log_level=log_level
        )


if __name__ == "__main__":
    # 解析命令行参数
    args = parse_arguments()
    
    # 启动服务器
    start_server(args)

